package com.juku2024.juku

import android.os.Bundle
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.juku2024.juku.adapter.CategoryListAdapter
import com.juku2024.juku.base.BaseActivity
import com.juku2024.juku.tools.WrapGridLayoutManager
import com.juku2024.juku.viewmodel.AlbumViewModel
import com.juku2024.juku.widget.HeaderView
import com.juku2024.juku.widget.LoadingView

class AlbumActivity: BaseActivity() {

    private lateinit var header: HeaderView
    private lateinit var loadingView: LoadingView
    private lateinit var albumRecycler: RecyclerView
    
    private val viewModel by lazy { getViewModel(AlbumViewModel::class.java) }

    override fun getLayoutResId(): Int {
        return R.layout.activity_album_list
    }

    override fun initView() {
        super.initView()
        header = findViewById(R.id.header_album_list)
        albumRecycler = findViewById(R.id.albumRecycler)
        loadingView = findViewById(R.id.loadingView_album_list)
        
        
        albumRecycler.layoutManager = WrapGridLayoutManager(this, 3)
    }

    override fun init(savedInstanceState: Bundle?) {
        val name = intent?.getStringExtra("album_name")?:""
        header.setTitle(name)

        val id = intent?.getLongExtra("album_id", 0L)?:0L
        if (id <= 0L) {
            loadingView.showEmptyStatus(getString(R.string.category_list_empty))
            return
        }
        val version = intent?.getIntExtra("album_version", 0)?:0
        loadingView.showLoading()
        doHttpAlbum(id, version)
    }

    private fun doHttpAlbum(id: Long, version: Int) {
        viewModel.getAlbumList(id, version, {
            if (isActivityNotActive()) return@getAlbumList
            loadingView.hideLoading()
            if (it.data.isNullOrEmpty()) {
                loadingView.showEmptyStatus(getString(R.string.category_list_empty))
                return@getAlbumList
            }
            val adapter = CategoryListAdapter(it.data)
            adapter.setOnItemClickListener { _, _, position ->
                VideoDetailActivity.toVideoDetail(this, adapter.data[position].id, adapter.data[position].name)
            }
            albumRecycler.layoutManager = GridLayoutManager(this, 3)
            albumRecycler.adapter = adapter
        }, {
            if (isActivityNotActive()) return@getAlbumList
            loadingView.hideLoading()
            loadingView.showErrorStatus(
                    getString(R.string.error_retry_list),
                    getString(R.string.retry)
            ) {
                loadingView.showLoading()
                loadingView.postDelayed({
                    if (isActivityNotActive()) return@postDelayed
                    doHttpAlbum(id, version)
                }, 1000)
            }
        })
    }
}